import geopandas as gpd
import pandas as pd
from bpy.types import Operator
import bmesh
import bpy
import math
import numpy
import sys
from mathutils import Vector, Matrix, noise, Quaternion
sys.path.extend(['', 'D:\\blender-2.92.0-windows64\\2.92\\python\\bin\\python37.zip', 'D:\\blender-2.92.0-windows64\\2.92\\python\\DLLs', 'D:\\blender-2.92.0-windows64\\2.92\\python\\lib', 'D:\\blender-2.92.0-windows64\\2.92\\python\\bin',
                'C:\\Users\\tomye\\AppData\\Roaming\\Python\\Python37\\site-packages', 'D:\\blender-2.92.0-windows64\\2.92\\python', 'D:\\blender-2.92.0-windows64\\2.92\\python\\lib\\site-packages'])

class Draw_Wall_Op(Operator):
    bl_idname = "object.draw_wall"
    bl_label = "draw wall"
    bl_description = "draw a wall"
    
    def execute(self,context):
        data = gpd.read_file(r"C:\Users\tomye\Documents\中线.geojson")
        offsetX = data.geometry[0].centroid.x
        offsetY = data.geometry[0].centroid.y
        offsetZ = 0.0
        print(data.geometry.centroid)
        names = []

        
        # create the material
        new_mat = bpy.data.materials.new(name="myMaterial")

        new_mat.use_nodes = True
        nodes = new_mat.node_tree.nodes
        material_output = nodes.get("Material Output")
        node_checker_texture = nodes.new(type="ShaderNodeTexChecker")
        
        node_checker_texture.inputs[1].default_value = (0.0596932, 0.0718455, 0.8, 1)
        node_checker_texture.inputs[2].default_value = (0.0204486, 0.2, 0.0251988, 1)

        links = new_mat.node_tree.links
        new_link = links.new(node_checker_texture.outputs[0],material_output.inputs[0])
        
        
        for index, row in data.iterrows():
            name = row['管道编码']
            x1 = row.geometry.coords.xy[0][0]-offsetX
            y1 = row.geometry.coords.xy[1][0]-offsetY
            z1 = row['起点高程']
            x2 = row.geometry.coords.xy[0][1]-offsetX
            y2 = row.geometry.coords.xy[1][1]-offsetY
            z2 = row['终点高程']
            if name in names:
                print(name + "已经存在")
            else:
                names.append(name)
                # Looping to create the grid
                verts = [(x1,y1,z1),(x2,y2,z2),(x2,y2,z2+2),(x1,y1,z1+2)]
                faces = [(0,1,2,3)]

                # Create Mesh Datablock
                mesh = bpy.data.meshes.new(name)
                mesh.from_pydata(verts, [], faces)

                obj = bpy.data.objects.new(name, mesh)
                bpy.context.scene.collection.objects.link(obj)
                obj.data.materials.append(new_mat)
                print(name)
        
        print(offsetX)
        print(offsetY)
        return {'FINISHED'}